package tech.wetech.admin.modules.system.web;

import com.github.pagehelper.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.dao.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import tech.wetech.admin.core.annotation.SystemLog;
import tech.wetech.admin.core.utils.Result;
import tech.wetech.admin.modules.base.query.PageQuery;
import tech.wetech.admin.modules.base.web.BaseCrudController;
import tech.wetech.admin.modules.system.enums.Channel;
import tech.wetech.admin.modules.system.enums.PayPattern;
import tech.wetech.admin.modules.system.enums.PosType;
import tech.wetech.admin.modules.system.po.Company;
import tech.wetech.admin.modules.system.po.DaoRu;
import tech.wetech.admin.modules.system.po.Pos;
import org.springframework.ui.Model;
import tech.wetech.admin.modules.system.service.CompanyService;
import tech.wetech.admin.modules.system.service.PosService;
import tech.wetech.admin.modules.system.vo.FileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lu
 * @description 设备信息管理
 * @date 2019年07月05日 15:34
 */
@Controller
@RequestMapping("/pos")
public class PosController extends BaseCrudController<Pos> {

    private static final Logger LOGGER = LoggerFactory.getLogger(PosController.class) ;

    @Autowired
    private PosService posService;

    @Autowired
    private CompanyService companyService;

    @ModelAttribute("types")//
    public Channel[] resourceTypes() {
        return Channel.values();
    }

    @ModelAttribute("paytypes")//
    public PayPattern[] paytypes() {
        return PayPattern.values();
    }

    @ModelAttribute("postypes")//
    public PosType[] postypes() {
        return PosType.values();
    }

    @Autowired
    private RedisTemplate<String, String> stringredisTemplate;

    @GetMapping
    public String pos(Model model) {
        //绑定客户下拉框
        List<Company> list=companyService.queryAll();
        //绑定客户的是否需要配置设备的支付json
        List<Company> companylist=new ArrayList<>();
        for (Company company : list) {
            if (company.getIsEverySet()){
                companylist.add(company);
            }
        }
        model.addAttribute("companyList", companylist);
        return "system/pos";
    }

    @ResponseBody
    @GetMapping("/list")
    @Override
    public Result<List<Pos>> queryList(Pos pos, PageQuery pageQuery) {
        pageQuery.setOrderBy("id desc");
        Page<Pos> page = (Page<Pos>) posService.queryList(pos, pageQuery);
        List<Pos> pos1 = new ArrayList<>();
       page.forEach(c -> {
            c.setChannelInfos(posService.selectpayCompanyInfo(c.getPosNo()));
           pos1.add(c);
        });
        return Result.success(pos1).addExtra("total", page.getTotal());
    }

    /*
    ** @author lu
    * @date 2019/8/30 10:21
    * @param [daoRu]
    * @return tech.wetech.admin.core.utils.Result
    * @description 导入获取txt的内容
    */
    @ResponseBody
    @PostMapping("/dao")
    public Result daoRU(DaoRu daoRu) {
        posService.daoRU(daoRu);
        return Result.success();
    }

    @ResponseBody
    @PostMapping("/shang")
    public String shang(MultipartHttpServletRequest multipartRequst) {

        if(multipartRequst == null){
            return "服务请求失败,MultipartHttpServletRequest空指针";
        }
        System.out.println(multipartRequst.getParameter("mchid"));
        MultipartFile multipartFile = multipartRequst.getFile("files");
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();
            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName = multipartRequst.getParameter("mchid");//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath ="/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/";//获取项目路径到webapp
            //String filepath ="D:\\temp";
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }
            try {
                multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        }
        return "上传失败";
    }

    @ResponseBody
    @PostMapping("/abcpr")
    public String abcpr(MultipartHttpServletRequest multipartRequst) {

        if(multipartRequst == null){
            return "服务请求失败,MultipartHttpServletRequest空指针";
        }
        System.out.println(multipartRequst.getParameter("mchid"));
        MultipartFile multipartFile = multipartRequst.getFile("files");
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();
            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName = multipartRequst.getParameter("mchid");//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath ="/usr/local/app/apache-tomcat-9.0.24/abc/";//获取项目路径到webapp
            //String filepath ="D:\\temp";
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }
            try {
                multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        }
        return "上传失败";
    }

    @ResponseBody
    @PostMapping("/add")
    @SystemLog("设备管理新增")
    @RequiresPermissions("pos:create")
    @Override
    public Result create(Pos pos) {
        posService.createPos(pos);
        return Result.success();
    }


    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("pos:update")
    @SystemLog("设备管理修改")
    @Override
    public Result update(Pos pos) {
        posService.updatePos(pos);
        flushdb();
        return Result.success();
    }

    @ResponseBody
    @SystemLog("设备管理删除")
    @RequiresPermissions("pos:delete")
    @PostMapping("/delete-batch")
    @Override
    public Result deleteBatchByIds(@RequestParam("id") Object[] ids) {
        posService.deleteBatchByIds(ids);
        flushdb();
        return Result.success();
    }

    /**
     * @author lu
     * @date 2020/4/7 15:37
     * @param:
     * @return void
     * @description 清空当前redis数据库
     */
    public void flushdb() {
        stringredisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }


    //
    @ResponseBody
    @PostMapping("/lakalapr")
    public String lakalapr(MultipartHttpServletRequest multipartRequst) {

        if(multipartRequst == null){
            return "服务请求失败,MultipartHttpServletRequest空指针";
        }
        System.out.println(multipartRequst.getParameter("appid"));
        MultipartFile multipartFile = multipartRequst.getFile("files");
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();
            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName ="lakalapr" + multipartRequst.getParameter("appid");//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath ="/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/";//获取项目路径到webapp
            //String filepath ="D:\\temp";
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }
            try {
                multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        }
        return "上传失败";
    }

    @ResponseBody
    @PostMapping("/lakalapu")
    public String lakalapu(MultipartHttpServletRequest multipartRequst) {

        if(multipartRequst == null){
            return "服务请求失败,MultipartHttpServletRequest空指针";
        }
        System.out.println(multipartRequst.getParameter("appid"));
        MultipartFile multipartFile = multipartRequst.getFile("files");
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();
            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName ="lakalapu" + multipartRequst.getParameter("appid");//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath ="/usr/local/app/apache-tomcat-9.0.24/webapps/apiclient_cert/";//获取项目路径到webapp
            //String filepath ="D:\\temp";
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }
            try {
                multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        }
        return "上传失败";
    }
}
